import type { RouteRecordRaw } from 'vue-router';
import { router } from '@/router';
import type { AppRouteRecordRaw } from '@/router/routes/types';
import { DEFAULT_LAYOUT } from '@/router/routes/base';

// 组件映射表，用于动态导入组件
const viewModules = import.meta.glob('../views/**/*.vue');
const layoutModules = {
  'default': DEFAULT_LAYOUT
};
export function getAvailableViewPaths() {
  const paths = Object.keys(viewModules);
  console.log('可用的组件路径:', paths);
  return paths;
}

/**
 * 检查是否是外部链接
 * @param path 路径
 */
function isExternalLink(path: string) {
  return /^(https?:|mailto:|tel:)/.test(path);
}

/**
 * 检查组件是否存在
 * @param component 组件路径
 */
function isComponentExists(component: string | undefined): boolean {
  if (!component) {
    return false;
  }

  if (component === 'default' || component === 'LAYOUT') {
    return true;
  }

  // 直接使用路径导入，比如 @/views/xxx/index.vue
  if (component.startsWith('@/')) {
    const path = component.replace('@/', '../');
    const exists = !!viewModules[path];
    return exists;
  }

  // 处理以 ../ 开头的相对路径
  if (component.startsWith('../')) {
    const exists = !!viewModules[component];
    if (exists) return true;
  }

  // 简写路径转换，比如 user/list -> @/views/user/list/index.vue
  const viewPath = `../views/${component}.vue`;
  if (viewModules[viewPath]) {
    return true;
  }

  // 检查更简化的路径 (新增) - 支持 manager/dailyNotice -> ../views/manager/dailyNotice.vue
  const fullViewPath = `../views/${component}.vue`;
  if (viewModules[fullViewPath]) {
    return true;
  }

  // 支持 manager/dailyNotice -> ../views/manager/dailyNotice/index.vue
  const indexPath = `../views/${component}/index.vue`;
  if (viewModules[indexPath]) {
    return true;
  }

  // 支持 user/userinfo -> ../views/user/userinfo.vue
  const indexComponentPath = `../views/${component}.vue`;
  if (viewModules[indexComponentPath]) {
    return true;
  }

  // 尝试加载不带 .vue 后缀的路径
  const pathWithoutExt = component.endsWith('.vue') ? component : `${component}.vue`;
  const withoutExtPath = `../views/${pathWithoutExt}`;
  if (viewModules[withoutExtPath]) {
    return true;
  }

  return false;
}

/**
 * 动态导入组件
 * @param component 组件路径
 */
function loadComponent(component: string | undefined) {
  if (!component) {
    return () => import('@/views/not-found/index.vue');
  }

  if (component === 'default' || component === 'LAYOUT') {
    return layoutModules.default;
  }

  // 直接使用路径导入，比如 @/views/xxx/index.vue
  if (component.startsWith('@/')) {
    const path = component.replace('@/', '../');
    if (viewModules[path]) {
      return viewModules[path];
    }
    return () => import('@/views/not-found/index.vue');
  }

  // 处理以 ../ 开头的相对路径
  if (component.startsWith('../')) {
    if (viewModules[component]) {
      return viewModules[component];
    }
  }

  // 简写路径转换，比如 user/list -> @/views/user/list/index.vue
  const viewPath = `../views/${component}.vue`;
  if (viewModules[viewPath]) {
    return viewModules[viewPath];
  }

  // 检查更简化的路径 (新增) - 支持 manager/dailyNotice -> ../views/manager/dailyNotice.vue
  const fullViewPath = `../views/${component}.vue`;
  if (viewModules[fullViewPath]) {
    return viewModules[fullViewPath];
  }

  // 支持 manager/dailyNotice -> ../views/manager/dailyNotice/index.vue
  const indexPath = `../views/${component}/index.vue`;
  if (viewModules[indexPath]) {
    return viewModules[indexPath];
  }

  // 支持 user/userinfo -> ../views/user/userinfo.vue
  const indexComponentPath = `../views/${component}.vue`;
  if (viewModules[indexComponentPath]) {
    return viewModules[indexComponentPath];
  }

  // 尝试加载不带 .vue 后缀的路径
  const pathWithoutExt = component.endsWith('.vue') ? component : `${component}.vue`;
  const withoutExtPath = `../views/${pathWithoutExt}`;
  if (viewModules[withoutExtPath]) {
    return viewModules[withoutExtPath];
  }

  // 最后尝试从默认路径导入，若不存在则显示404页面
  return () => import('@/views/not-found/index.vue');
}

/**
 * 格式化后端返回的路由数据
 * @param routes 后端返回的路由数据
 */
export function formatDynamicRoutes(routes: any): AppRouteRecordRaw[] {
  // 处理 mock 接口返回的数据嵌套问题
  let routesToFormat = routes;

  if (!routes) {
    return [];
  }

  // 处理可能的多种返回格式
  if (typeof routes === 'object' && !Array.isArray(routes)) {
    // 1. 标准响应体格式 {data, success, msg, code}
    if ('data' in routes && routes.data !== undefined && routes.data !== null) {
      routesToFormat = routes.data;
    }
    // 2. 其他对象情况，可能是其他自定义结构
    else {
      routesToFormat = routes;
    }
  }
  // 3. 数组情况
  else if (Array.isArray(routes)) {
    // 可能是直接的路由数组
    routesToFormat = routes;
  }

  const formattedRoutes: AppRouteRecordRaw[] = [];

  // 确保 routesToFormat 是数组，如果不是，尝试转换
  if (!Array.isArray(routesToFormat)) {
    // 如果是对象，尝试转换成数组
    if (typeof routesToFormat === 'object' && routesToFormat !== null) {
      const keys = Object.keys(routesToFormat);
      if (keys.length > 0) {
        // 如果有数字键，可能是类数组对象
        const numberKeys = keys.filter(k => !isNaN(Number(k)));
        if (numberKeys.length > 0) {
          routesToFormat = numberKeys.map(k => routesToFormat[k]);
        } else {
          // 否则将整个对象放入数组
          routesToFormat = [routesToFormat];
        }
      } else {
        routesToFormat = [];
      }
    } else {
      routesToFormat = [];
    }
  }

  // 如果 routesToFormat 是空数组，直接返回空数组
  if (routesToFormat.length === 0) {
    return [];
  }

  // 遍历路由数据
  routesToFormat.forEach(route => {
    if (!route) {
      return;
    }

    // 检查并确保组件路径正确
    if (route.component) {
      isComponentExists(route.component);
    }

    // 检查并输出meta属性
    if (!route.meta) {
      // 确保路由有meta属性
      route.meta = {
        locale: String(route.name || '未命名'),
        requiresAuth: true,
        roles: ['*']
      };
    }

    // 检查是否是外部链接
    const isExternal = route.path && isExternalLink(route.path);

    // 如果是外部链接，直接添加
    if (isExternal) {
      formattedRoutes.push({
        path: route.path,
        name: route.name,
        component: DEFAULT_LAYOUT,
        meta: route.meta,
        children: []
      });
      return;
    }

    // 检查组件是否存在，不存在则不添加该路由（根节点除外）
    const componentExists =
      route.component === 'default' || route.component === 'LAYOUT' || isComponentExists(route.component);
    const isParentRoute = route.children && route.children.length > 0;

    // 处理父级路由
    if (isParentRoute) {
      // 递归处理子路由
      const formattedChildren = formatDynamicRoutes(route.children);

      // 即使没有有效子路由，也创建父级路由（修改这里，避免过滤掉父级）
      const formattedRoute: AppRouteRecordRaw = {
        path: route.path,
        name: route.name,
        redirect: route.redirect,
        component: loadComponent(route.component || 'default'),
        meta: route.meta,
        children: formattedChildren
      };

      formattedRoutes.push(formattedRoute);
    }
    // 处理叶子节点
    else if (componentExists) {
      // 如果是叶子节点且组件存在，则添加该路由
      const formattedRoute: AppRouteRecordRaw = {
        path: route.path,
        name: route.name,
        redirect: route.redirect,
        component: loadComponent(route.component || 'default'),
        meta: route.meta
      };

      if (route.children) {
        formattedRoute.children = [];
      }

      formattedRoutes.push(formattedRoute);
    } else {
      // 如果组件不存在，尝试使用404组件
      const formattedRoute: AppRouteRecordRaw = {
        path: route.path,
        name: route.name,
        redirect: route.redirect,
        component: () => import('@/views/not-found/index.vue'),
        meta: route.meta
      };

      if (route.children) {
        formattedRoute.children = [];
      }

      formattedRoutes.push(formattedRoute);
    }
  });

  return formattedRoutes;
}

/**
 * 添加动态路由
 * @param routes 格式化后的路由数据
 */
export function addDynamicRoutes(routes: AppRouteRecordRaw[]) {
  routes.forEach(route => {
    const routeName = route.name ? String(route.name) : '';

    // 如果是外部链接，不需要添加到路由注册表中
    if (route.path && isExternalLink(route.path)) {
      return;
    }

    // 如果路由已存在，先移除它
    if (routeName && router.hasRoute(routeName)) {
      router.removeRoute(routeName);
    }

    // 添加新路由
    try {
      // 确保路由对象格式正确
      const routeToAdd = {
        ...route,
        name: routeName,
        component: typeof route.component === 'string' ? loadComponent(route.component) : route.component
      };

      router.addRoute(routeToAdd as RouteRecordRaw);
    } catch (error) {
      console.error('addDynamicRoutes - 路由添加失败:', routeName, error);
      // 尝试添加一个简单的404路由作为备选
      try {
        const fallbackRoute = {
          path: route.path,
          name: routeName,
          component: () => import('@/views/not-found/index.vue'),
          meta: route.meta
        };
        router.addRoute(fallbackRoute as RouteRecordRaw);
      } catch (fallbackError) {
        console.error('addDynamicRoutes - 备选路由也失败:', routeName, fallbackError);
      }
    }
  });
}

/**
 * 重置路由
 */
export function resetRouter() {
  router.getRoutes().forEach(route => {
    if (route.name && route.name !== 'login' && route.name !== 'notFound') {
      router.removeRoute(route.name);
    }
  });
}
